const http = require('http');
const fs = require('fs');
const {httpReadFile, httpReadFileWithData, readFile, writeFile} = require('./utils/file-util')
const server = http.createServer();
const url = require('url')
const {query} = require('./dao/dao')
const message = require('./dao/message')
const {Message} = require('./entity/message')

server.listen(3309, function () {
    console.log("留言板服务启动成功~");
})


server.on('request', function (request, response) {

    const {pathname, query} = url.parse(request.url, true)

    // 查询数据
    if (pathname === '/') {


        Promise.all([message.select(query), message.count(query)]).then(res => {

            const total = [];
            const page = Math.ceil(res[1][0].total / (query.pageSize || 5));
            for (let i = 1; i <= page; i++) {
                total.push(i)
            }
            httpReadFileWithData('./views/index.html', response, {list: res[0], total})
        })
    }
    // 处理 这个路径的时候进行处理
    else if (pathname.startsWith('/node_modules')) {
        httpReadFile("." + pathname, response)
    }
    // 处理 这个路径的时候进行处理
    else if (pathname.startsWith('/public')) {
        httpReadFile("." + pathname, response)
    }

    // 增加数据的处理
    else if (pathname === '/save') {
        if (query.name != '' || query.content != '') {
            const messageContent = new Message(query.name, query.content);
            message.insert(messageContent).then(res => {
                response.statusCode = 302;
                response.setHeader('location', '/')
                response.end();
            })
        }

    }
    // 添加数据的界面
    else if (pathname === '/add') {
        httpReadFile('./views/add.html', response)
    } else if (pathname === '/del') {
        message.deleteMessage(query.id).then(res => {
            response.statusCode = 302;
            response.setHeader('location', '/');
            response.end();
        })
    } else {
        httpReadFile('./views/error.html', response)
    }
})


